//
//  ModelData.swift
//  Landmarks
//
//  Created by 温哲 on 2021/2/10.
//

import Combine
import Foundation

/// 这个真不理解是干啥的

final class ModelData: ObservableObject {
    @Published var landmarks: [Landmark] = load("landmarkData.json")
    // 此处加载后不会修改数据 因此 不需要 @Published
    var hikes: [Hike] = load("hikeData.json")
    @Published var profile = Profile.default

    var features: [Landmark] {
        /** 写法有点怪 据说是语法糖
         let numbers = [1,2,5,4,3,6,8,7]
             sortNumbers = numbers.sorted(by: { (a, b) -> Bool in
               return a < b
             })
         print("numbers -" + "\(sortNumbers)")
         ---使用$0,$1---
         let numbers = [1,2,5,4,3,6,8,7]
          var sortNumbers = numbers.sorted(by: {$0 < $1})
          print("numbers -" + "\(sortNumbers)")
         */
        landmarks.filter { $0.isFeatured }
    }

    var categories: [String: [Landmark]] {
        Dictionary(
            grouping: landmarks, by: { $0.category.rawValue }
        )
    }
}

func load<T: Decodable>(_ filename: String) -> T {
    let data: Data
    guard let file = Bundle.main.url(forResource: filename, withExtension: nil) else {
        fatalError("Couldn't find \(filename) in main bundle.")
    }
    do {
        data = try Data(contentsOf: file)
    } catch {
        fatalError("Couldn't load \(filename) from main bundle:\n\(error)")
    }
    do {
        let decoder = JSONDecoder()
        return try decoder.decode(T.self, from: data)
    } catch {
        fatalError("Couldn't parse \(filename) as \(T.self):\n\(error)")
    }
}
